import Taro from '@tarojs/taro'
import { get, post } from './request/request'
import { showModal } from './tools/public.js'
import apiUrl from './urls.js'
import { getLocalUserInfo } from './userInfo.js'
// 5 => 事项办理

const tmplIdsMap = []

// 获取模版Id列表
async function getTemplateIds() {
  const res = await get(apiUrl.getTemplateIdsUrl)
  const data = res || []
  tmplIdsMap.splice(0)
  tmplIdsMap.push(...data)
}
 getTemplateIds(0)

// 存储当前用户订阅状态
async function setSubsTplIds(list) {
  const { openId } = getLocalUserInfo()
  await post(apiUrl.setSubsTplIdsUrl,{list,openId})
}

function getTplIds(types, isFilter = true) {
  const tmpMap = {}
  tmplIdsMap.forEach(item => {
    tmpMap[item.msgType] = item.templateId
  })

  const result = types.map(type => tmpMap[type])

  if (!isFilter) return result

  return result.filter(v => v)
}
// function getType(id) {
//   const item = tmplIdsMap.find(item => item.templateId === id)
//   return item ? +item.msgType : null
// }

// 发起订阅消息请求
export default function requestSubscribeMessage(tmplIdsName = [5]) {
  return new Promise((resolve, reject) => {
    Taro.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log(res)
        const itemSettings = res.subscriptionsSetting.itemSettings || ''
        let hasReject = res.subscriptionsSetting.mainSwitch ? -1 : 0
        if (itemSettings) {
          if (hasReject === -1) {
            const index = Object.values(itemSettings).indexOf('reject')
            hasReject = index
          }
        }
        // wx.openSetting({
        //   withSubscriptions: true,
        //   success(res) {
        //     console.log('授权信息', res)
        //   }
        // })
        if (hasReject > -1) {
          return showModal('提示', '为了给您提供更好的服务，请打开设置', {
            showCancel: true,
            confirmText: '好的',
            success: res => {
              if (res.confirm) {
                Taro.openSetting({
                  withSubscriptions: true,
                  success(res) {
                    console.log('授权信息', res)
                    if (
                      !res.subscriptionsSetting ||
                      !res.subscriptionsSetting.mainSwitch
                    ) {
                      return
                    }
                    sendSubscribe(resolve, reject, tmplIdsName)
                  }
                })
              }
            }
          })
        } else {
          sendSubscribe(resolve, reject, tmplIdsName)
        }
      }
    })
  })
}

 function sendSubscribe(resolve, reject, tmplIdsName) { 
  const tmplIds = getTplIds(tmplIdsName)
  // console.log('tmplIds=>', tmplIds)
  // 没有找到可订阅的模版id
  if (!tmplIds.length) {
    resolve(tmplIdsName.map(() => null))
    // reject(new Error('小程序未配置对应通知'))
  }
  // console.log('模版类型', tmplIdsName, '模版Id', tmplIds)
   Taro.requestSubscribeMessage({
    tmplIds,
    success: async ({ errMsg, ...tplIds }) => {
      if (errMsg === 'requestSubscribeMessage:ok') {
        // 将订阅状态发送到服务器
      await  setSubsTplIds(
          Object.keys(tplIds).map(id => ({
            templateId: id,
            authStatus: tplIds[id]
          }))
        )

        // 返回订阅状态数组 [true, false, null] true=>成功订阅 false=>未订阅 null=>模版Id不存在
        const status = getTplIds(tmplIdsName, false).map(id => {
          if (!tplIds[id]) return null
          return tplIds[id] === 'accept'
        })
        resolve(status)
        return
      }
      reject(new Error(`消息订阅异常(${errMsg})`))
    },
    fail: error => {
      console.log('error', error)
      // 禁止发送订阅消息
      if (error.errCode === 20004) {
        resolve([])
        return
      }
      if (
        error.errMsg ===
        'requestSubscribeMessage:fail can only be invoked by user TAP gesture.'
      ) {
        resolve([])
        return
      }
      reject(new Error(`消息订阅失败(${error.errMsg})`))
    }
  })
}
